package jupiter.util;

//import java.sql.*;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import jupiter.message.Message;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DBConnection {
	static Logger logger = LoggerFactory.getLogger(DBConnection.class);
	private static DataSource getDataSource(){
		InitialContext ictx = null;
		try {
			ictx = new InitialContext();
		} catch (NamingException e) {
			logger.error("NamingException", e);
		}
		DataSource ds = null;
		try {
			ds = (DataSource) ictx.lookup( "java:comp/env/jdbc/db" );
		} catch (NamingException e) {
			logger.error("NamingException", e);
		}
		return ds;
	}
   
	public static DataSource ds = DBConnection.getDataSource();
    /**
     * Calls back a function on an object with a stateument
     * @param object
     * @param method_name
     * @return
     */

	private Connection conn = null;
	protected PreparedStatement pstmt= null;
	protected ResultSet rs = null;
	protected ResultSet keyRS = null;
	public DBConnection(){
		
	}
	public Object run(Object o) throws SQLException {
		return run();
	}
	public Object run() throws SQLException {
		return null;
	}
	
	public PreparedStatement prepareStatement(String sql) throws SQLException{
		if(pstmt != null)
			pstmt.close();
		pstmt = conn.prepareStatement(sql);
		return pstmt;
	}
	public PreparedStatement prepareStatement(String sql, int statement) throws SQLException{
		if(pstmt != null)
			pstmt.close();
		pstmt = conn.prepareStatement(sql, statement);
		return pstmt;
	}
	public void executeQuery() throws SQLException {
		if(rs != null) rs.close();
		rs = pstmt.executeQuery();
	}
	public void getGeneratedKeys() throws SQLException {
		if(keyRS != null) keyRS.close();
		keyRS = pstmt.getGeneratedKeys();
	}
	public Object exec() throws SQLException{
		return exec(null);
	}
	public Object exec(Object o) throws SQLException{
		Object ret = null;
	    try{
	    	conn = DBConnection.ds.getConnection();
	    	ret = run(o);
	    	if(keyRS != null)
	    		keyRS.close();
			if(rs != null)
				rs.close();
			pstmt.close();
	        conn.close();
	    }catch(SQLException e){
	    	
	    	try{
	    		if(rs != null)    rs.close();
	    		if(keyRS != null) keyRS.close();
	    		pstmt.close();
		        conn.close();
	        } catch(SQLException close_e){
				logger.error("SQLException: ERROR in closing connections", close_e);
	        }
			//logger.error("SQLException", e);
			//should probably throw this guy
	    	throw e;
	    }
    	
        return ret;
	}

}
